Imports ExpertPdf.HtmlToPdf
Imports System.Drawing


Partial Class _Default
    Inherits System.Web.UI.Page

    Protected Sub lnkBtnSettings_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles lnkBtnSettings.Click
        If Not Page.IsValid Then
            Return
        End If
        If pnlRenderMoreOptions.Visible Then

            pnlRenderMoreOptions.Visible = False
            lnkBtnSettings.Text = "More Converter Settings >>"
        Else
            pnlRenderMoreOptions.Visible = True
            lnkBtnSettings.Text = "<< Hide Settings"
        End If
    End Sub

    Protected Sub radioConvertToPDF_CheckedChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles radioConvertToPDF.CheckedChanged
        pnlImageRenderOptions.Visible = Not CType(sender, RadioButton).Checked
        pnlPDFRenderOptions.Visible = CType(sender, RadioButton).Checked
        cbGenerateSelectablePdf.Checked = False
        cbEmbedFonts.Visible = radioConvertToSelectableText.Checked
        cbFitWidth.Visible = Not radioConvertToImage.Checked
        cbLiveLinksEnabled.Visible = Not radioConvertToImage.Checked
        cbBookmarks.Visible = Not radioConvertToImage.Checked
        cbJpegCompression.Visible = Not radioConvertToImage.Checked
    End Sub

    Protected Sub radioConvertToImage_CheckedChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles radioConvertToImage.CheckedChanged
        pnlImageRenderOptions.Visible = CType(sender, RadioButton).Checked
        pnlPDFRenderOptions.Visible = Not CType(sender, RadioButton).Checked
        cbEmbedFonts.Visible = radioConvertToSelectableText.Checked
        cbFitWidth.Visible = Not radioConvertToImage.Checked
        cbLiveLinksEnabled.Visible = Not radioConvertToImage.Checked
        cbBookmarks.Visible = Not radioConvertToImage.Checked
        cbJpegCompression.Visible = Not radioConvertToImage.Checked
    End Sub

    Protected Sub radioAutodetectWebPageSize_CheckedChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles radioAutodetectWebPageSize.CheckedChanged
        pnlCustomPageSize.Visible = Not CType(sender, RadioButton).Checked
    End Sub

    Protected Sub radioCustomWebPageSize_CheckedChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles radioCustomWebPageSize.CheckedChanged
        pnlCustomPageSize.Visible = CType(sender, RadioButton).Checked
    End Sub

    Protected Sub cbShowheader_CheckedChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles cbShowheader.CheckedChanged
        pnlPDFHeaderOptions.Visible = CType(sender, CheckBox).Checked
    End Sub

    Protected Sub cbShowFooter_CheckedChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles cbShowFooter.CheckedChanged
        pnlPDFFooterOptions.Visible = CType(sender, CheckBox).Checked
    End Sub

    Protected Sub btnConvert_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnConvert.Click
        lblConvertMessage.Visible = False

        If Not Page.IsValid Then
            Return
        End If

        Dim urlToConvert As String = textBoxWebPageURL.Text.Trim()

        Dim downloadName As String = "Report"
        Dim downloadBytes As Byte() = Nothing

        If (radioConvertToPDF.Checked Or radioConvertToSelectableText.Checked) Then
            downloadName += ".pdf"
            Dim pdfConverter As PdfConverter = GetPdfConverter()
            downloadBytes = pdfConverter.GetPdfBytesFromUrl(urlToConvert)
        Else
            downloadName += "." + ddlImageFormat.SelectedValue
            Dim imgConverter As ImgConverter = GetImgConverter()
            downloadBytes = imgConverter.GetImageFromUrlBytes(urlToConvert, GetImageFormat(CType([Enum].Parse(GetType(RenderImageFormat), ddlImageFormat.SelectedValue), RenderImageFormat)))
        End If


        Dim response As System.Web.HttpResponse = System.Web.HttpContext.Current.Response
        response.Clear()
        response.AddHeader("Content-Type", "binary/octet-stream")
        response.AddHeader("Content-Disposition", "attachment; filename=" & downloadName & "; size=" & downloadBytes.Length.ToString())
        response.Flush()
        response.BinaryWrite(downloadBytes)
        response.Flush()
        response.End()
    End Sub

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        lblConvertMessage.Visible = False

        If Not IsPostBack Then
            LoadImageFormats()
            LoadPDFFormats()
            LoadPageOrientations()
            LoadColors()
            LoadCompressionLevels()
            LoadPdfSubsets()
        End If
    End Sub

    Private Sub LoadImageFormats()
        Dim imageFormats As String()
        imageFormats = [Enum].GetNames(GetType(RenderImageFormat))
        ddlImageFormat.DataSource = imageFormats
        ddlImageFormat.DataBind()
        ddlImageFormat.SelectedValue = RenderImageFormat.Jpeg.ToString()
    End Sub

    Private Sub LoadCompressionLevels()
        Dim pdfCompressionLevels As String() = [Enum].GetNames(GetType(PdfCompressionLevel))
        ddlCompressionLevel.DataSource = pdfCompressionLevels
        ddlCompressionLevel.DataBind()
        ddlCompressionLevel.SelectedValue = PdfCompressionLevel.Normal.ToString()
    End Sub

    Private Sub LoadPDFFormats()

        Dim pdfFormats As String() = [Enum].GetNames(GetType(PdfPageSize))
        ddlPDFPageFormat.DataSource = pdfFormats
        ddlPDFPageFormat.DataBind()
        ddlPDFPageFormat.SelectedValue = PdfPageSize.A4.ToString()
    End Sub

    Private Sub LoadColors()

        Dim colors As String() = [Enum].GetNames(GetType(KnownColor))

        ddlHeaderColor.DataSource = colors
        ddlHeaderColor.DataBind()
        ddlHeaderColor.SelectedValue = KnownColor.Black.ToString()

        ddlFooterTextColor.DataSource = colors
        ddlFooterTextColor.DataBind()
        ddlFooterTextColor.SelectedValue = KnownColor.Black.ToString()
    End Sub

    Private Sub LoadPageOrientations()

        Dim pdfPageOrientations As String() = [Enum].GetNames(GetType(PDFPageOrientation))
        ddlPageOrientation.DataSource = pdfPageOrientations
        ddlPageOrientation.DataBind()
        ddlPageOrientation.SelectedValue = PDFPageOrientation.Portrait.ToString()

    End Sub


    Private pdfStandards As String() = {"PDF", "PDF/A", "PDF/X", "PDF/SiqQA", "PDF/SiqQB"}
    Private Function GetPdfStandard(ByVal standardName As String) As PdfStandardSubset
        Select Case standardName

            Case "PDF"
                Return PdfStandardSubset.Full
            Case "PDF/A"
                Return PdfStandardSubset.Pdf_A_1b
            Case "PDF/X"
                Return PdfStandardSubset.Pdf_X_1a
            Case "PDF/SiqQA"
                Return PdfStandardSubset.Pdf_SiqQ_a
            Case "PDF/SiqQB"
                Return PdfStandardSubset.Pdf_SiqQ_b
            Case Else
                Return PdfStandardSubset.Full

        End Select
    End Function

    Private Sub LoadPdfSubsets()

        ddlPdfSubset.DataSource = pdfStandards
        ddlPdfSubset.DataBind()
        ddlPdfSubset.SelectedValue = "PDF"

    End Sub

    'Create a PdfConverter object
    Private Function GetPdfConverter() As PdfConverter

        Dim pdfConverterObj As PdfConverter = New PdfConverter()

        'pdfConverterObj.LicenseKey = "put your license key here"

        ' set the HTML page width in pixels
        ' the default value is 1024 pixels
        If (radioCustomWebPageSize.Checked) Then
            pdfConverterObj.PageWidth = Integer.Parse(textBoxCustomWebPageWidth.Text.Trim())
        Else
            pdfConverterObj.PageWidth = 0 'autodetect
        End If

        ' set if the generated PDF contains selectable text or an embedded image - default value is true
        pdfConverterObj.PdfDocumentOptions.GenerateSelectablePdf = cbGenerateSelectablePdf.Checked

        ' set the PDF page size
        pdfConverterObj.PdfDocumentOptions.PdfPageSize = CType([Enum].Parse(GetType(PdfPageSize), ddlPDFPageFormat.SelectedValue), PdfPageSize)
        ' set the PDF compression level
        pdfConverterObj.PdfDocumentOptions.PdfCompressionLevel = CType([Enum].Parse(GetType(PdfCompressionLevel), ddlCompressionLevel.SelectedValue), PdfCompressionLevel)
        ' set the PDF page orientation (portrait or landscape)
        pdfConverterObj.PdfDocumentOptions.PdfPageOrientation = CType([Enum].Parse(GetType(PDFPageOrientation), ddlPageOrientation.SelectedValue), PDFPageOrientation)
        ' set the PDF standard used to generate the PDF document
        pdfConverterObj.PdfStandardSubset = GetPdfStandard(ddlPdfSubset.SelectedItem.ToString())
        ' show or hide header and footer
        pdfConverterObj.PdfDocumentOptions.ShowHeader = cbShowheader.Checked
        pdfConverterObj.PdfDocumentOptions.ShowFooter = cbShowFooter.Checked
        'set the PDF document margins
        pdfConverterObj.PdfDocumentOptions.LeftMargin = Integer.Parse(textBoxLeftMargin.Text.Trim())
        pdfConverterObj.PdfDocumentOptions.RightMargin = Integer.Parse(textBoxRightMargin.Text.Trim())
        pdfConverterObj.PdfDocumentOptions.TopMargin = Integer.Parse(textBoxTopMargin.Text.Trim())
        pdfConverterObj.PdfDocumentOptions.BottomMargin = Integer.Parse(textBoxBottomMargin.Text.Trim())
        ' set if the HTTP links are enabled in the generated PDF
        pdfConverterObj.PdfDocumentOptions.LiveUrlsEnabled = cbLiveLinksEnabled.Checked
        ' set if the HTML content is resized if necessary to fit the PDF page width - default is true
        pdfConverterObj.PdfDocumentOptions.FitWidth = cbFitWidth.Checked
        ' set if the PDF page should be automatically resized to the size of the HTML content when FitWidth is false
        pdfConverterObj.PdfDocumentOptions.AutoSizePdfPage = True
        ' embed the true type fonts in the generated PDF document
        pdfConverterObj.PdfDocumentOptions.EmbedFonts = cbEmbedFonts.Checked
        'compress the images in PDF with JPEG to reduce the PDF document size - default is true
        pdfConverterObj.PdfDocumentOptions.JpegCompressionEnabled = cbJpegCompression.Checked
        ' set if the JavaScript is enabled during conversion 
        pdfConverterObj.ScriptsEnabled = cbScriptsEnabled.Checked

        pdfConverterObj.PdfHeaderOptions.HeaderText = textBoxHeaderText.Text
        pdfConverterObj.PdfHeaderOptions.HeaderTextColor = Color.FromKnownColor(CType([Enum].Parse(GetType(KnownColor), ddlHeaderColor.SelectedValue), KnownColor))
        pdfConverterObj.PdfHeaderOptions.HeaderSubtitleText = textBoxHeaderSubtitle.Text
        pdfConverterObj.PdfHeaderOptions.DrawHeaderLine = cbDrawHeaderLine.Checked

        pdfConverterObj.PdfFooterOptions.FooterText = textBoxFooterText.Text
        pdfConverterObj.PdfFooterOptions.FooterTextColor = Color.FromKnownColor(CType([Enum].Parse(GetType(KnownColor), ddlFooterTextColor.SelectedValue), KnownColor))
        pdfConverterObj.PdfFooterOptions.DrawFooterLine = cbDrawFooterLine.Checked
        pdfConverterObj.PdfFooterOptions.PageNumberText = textBoxPageNmberText.Text
        pdfConverterObj.PdfFooterOptions.ShowPageNumber = cbShowPageNumber.Checked

        If (cbBookmarks.Checked) Then
            pdfConverterObj.PdfBookmarkOptions.TagNames = New String() {"h1", "h2"}
        Else
            pdfConverterObj.PdfBookmarkOptions.TagNames = Nothing
        End If

        Return pdfConverterObj
    End Function

    Private Function GetImgConverter() As ImgConverter

        Dim imgConverterObj As ImgConverter = New ImgConverter()

        'set common properties
        If (radioCustomWebPageSize.Checked) Then
            imgConverterObj.PageWidth = Integer.Parse(textBoxCustomWebPageWidth.Text.Trim())
        End If

        imgConverterObj.ScriptsEnabled = cbScriptsEnabled.Checked

        Return imgConverterObj
    End Function

    Private Function GetImageFormat(ByVal imgFormat As RenderImageFormat) As System.Drawing.Imaging.ImageFormat

        If (imgFormat = RenderImageFormat.Bmp) Then
            Return System.Drawing.Imaging.ImageFormat.Bmp
        End If
        If (imgFormat = RenderImageFormat.Gif) Then
            Return System.Drawing.Imaging.ImageFormat.Gif
        End If
        If (imgFormat = RenderImageFormat.Jpeg) Then
            Return System.Drawing.Imaging.ImageFormat.Jpeg
        End If
        If (imgFormat = RenderImageFormat.Png) Then
            Return System.Drawing.Imaging.ImageFormat.Png
        End If
        If (imgFormat = RenderImageFormat.Tiff) Then
            Return System.Drawing.Imaging.ImageFormat.Tiff
        End If
        Return System.Drawing.Imaging.ImageFormat.Bmp
    End Function

    Protected Sub cvCustomPageWidth_ServerValidate(ByVal source As Object, ByVal args As System.Web.UI.WebControls.ServerValidateEventArgs) Handles cvCustomPageWidth.ServerValidate
        args.IsValid = True
        Dim width As Integer = 0
        Try
            width = Integer.Parse(textBoxCustomWebPageWidth.Text.Trim())
        Catch
            args.IsValid = False
            Return
        End Try
        args.IsValid = width >= 0
    End Sub

    Protected Sub cvLeftMargin_ServerValidate(ByVal source As Object, ByVal args As System.Web.UI.WebControls.ServerValidateEventArgs) Handles cvLeftMargin.ServerValidate
        args.IsValid = True
        Dim width As Integer = 0
        Try
            width = Integer.Parse(textBoxLeftMargin.Text.Trim())
        Catch
            args.IsValid = False
            Return
        End Try
        args.IsValid = width >= 0
    End Sub

    Protected Sub cvRightMargin_ServerValidate(ByVal source As Object, ByVal args As System.Web.UI.WebControls.ServerValidateEventArgs) Handles cvRightMargin.ServerValidate
        args.IsValid = True
        Dim width As Integer = 0
        Try
            width = Integer.Parse(textBoxRightMargin.Text.Trim())
        Catch
            args.IsValid = False
            Return
        End Try
        args.IsValid = width >= 0
    End Sub

    Protected Sub cvTopMargin_ServerValidate(ByVal source As Object, ByVal args As System.Web.UI.WebControls.ServerValidateEventArgs) Handles cvTopMargin.ServerValidate
        args.IsValid = True
        Dim width As Integer = 0
        Try
            width = Integer.Parse(textBoxTopMargin.Text.Trim())
        Catch
            args.IsValid = False
            Return
        End Try
        args.IsValid = width >= 0
    End Sub

    Protected Sub cvBottomMargin_ServerValidate(ByVal source As Object, ByVal args As System.Web.UI.WebControls.ServerValidateEventArgs) Handles cvBottomMargin.ServerValidate
        args.IsValid = True
        Dim width As Integer = 0
        Try
            width = Integer.Parse(textBoxBottomMargin.Text.Trim())
        Catch
            args.IsValid = False
            Return
        End Try
        args.IsValid = width >= 0
    End Sub

    Protected Sub radioConvertToSelectableText_CheckedChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles radioConvertToSelectableText.CheckedChanged
        pnlImageRenderOptions.Visible = Not CType(sender, RadioButton).Checked
        pnlPDFRenderOptions.Visible = CType(sender, RadioButton).Checked
        cbGenerateSelectablePdf.Checked = True
        cbEmbedFonts.Visible = radioConvertToSelectableText.Checked
        cbFitWidth.Visible = Not radioConvertToImage.Checked
        cbLiveLinksEnabled.Visible = Not radioConvertToImage.Checked
        cbBookmarks.Visible = Not radioConvertToImage.Checked
        cbJpegCompression.Visible = Not radioConvertToImage.Checked
    End Sub

End Class
